import mydialog from '@/components/mydialog/mydialog.vue'
import Vue from 'vue'
import  {Dialog,Drawer} from 'element-ui'
// console.log("=>(modifyDialog3.jsx:4) ElDialog,ElDraw", Dialog,Drawer);

function isFunction(obj) {
    return  obj&&(typeof obj === 'function')
}

export default async  function createDialog(options) {
    var  DynamicComponent =''
     var _targType=options?.tagType||'el-dialog'
   if(_targType=='el-dialog'){
     DynamicComponent=Dialog
   }  else if(_targType=='el-drawer'){
    DynamicComponent=Drawer
  }

    let modifyComResult = options&&options.components&&options.components.modify
    let modifyCom=undefined;
    if(isFunction(modifyComResult)){
        modifyCom=  await modifyComResult().then(res=>res&&res.default)
    }else{
        modifyCom=modifyComResult
    }






  let footerComResult = options&&options.components&&options.components.footer
  let footerCom=undefined;
  if(isFunction(footerComResult)){
    footerCom=  await footerComResult().then(res=>res&&res.default)
  }else{
    footerCom=footerComResult
  }


  let titleComResult = options&&options.components&&options.components.title
  let titleCom=undefined;
  if(isFunction(titleComResult)){
    titleCom=  await titleComResult().then(res=>res&&res.default)
  }else{
    titleCom=titleComResult
  }



  var _top=options?.top;
  if(!_top){
    _top=options.strictHeight?'0px':'2vh'
  }

    var formDialog = {
        name: 'FormDialog',
        data() {
            var self = this
            var promiseObject = {}
            return {
                sureText:options&&options.sureText||"确定",
                promiseObject,
                dialogVisible: false,
                fullscreen: false,
                modal: options && options.modal,
                hiddenSuccess: options?.hiddenSuccess,

                init() {
                    this.dialogVisible = true;


                    self.$nextTick(() => {
                        setTimeout(async () => {

                            var initDialogKey=options?._props?.initDialogFuncKey||'initByDialog';
                            await (self.$refs['modify'] && self.$refs['modify']?.[initDialogKey]({
                              ...options && options.data && options.data(),
                              dialogCom:self,
                            }));



                          await (self.$refs['footerRef'] && self.$refs['footerRef'].initByDialog({
                            ...options && options.data && options.data(),
                            dialogCom:self,
                            modifyCom:self.$refs['modify'] && self.$refs['modify'],
                          }));

                          await (self.$refs['titleRef'] && self.$refs['titleRef'].initByDialog({
                            ...options && options.data && options.data(),
                            dialogCom:self,
                            modifyCom:self.$refs['modify'] && self.$refs['modify'],
                          }));




                            setTimeout(()=>{
                              options&&options._onAfterComonentMounted&&options._onAfterComonentMounted()
                            });

                        }, 100)
                    })
                },
                loading: false,
                hiddenFooter: options?.hiddenFooter
            }
        },

        watch: {
            dialogVisible(isyes) {
                if (!isyes) {
                      this.closeDialog()
                }
            },
        },
        methods: {
            initPromise() {
                var self = this
                return new Promise((resolve, reject) => {
                    self.promiseObject = { resolve, reject }
                })
            },
            onevent() {
                var self = this
                return {
                    open() {
                      options?.onOpen?.()
                    },
                  closed() {
                    options?.onClose?.()

                    self.$refs['modify']&&
                    self.$refs['modify'].destroyed && self.$refs['modify'].destroyed &&
                    self.$refs['modify'].destroyed()

                    //关闭弹出框的option hook
                    options && options.destroyed && options.destroyed()
                    options && options.destroyed && options.destroyed()
                  },

                  opened() {
                    self;
                    var dialogCom=$($($(self.$el)[0]).find('.dialogClass')[0]);
                    const height = document.body.scrollHeight
                    if(_targType === 'el-drawer' && dialogCom) {
                      dialogCom[0].style.setProperty('height', height + 'px', 'important');
                    }

                    console.log("=>(modifyDialog3.jsx:135) options.strictHeight", options?.strictHeight);
                    if(options&&options.strictHeight){
                      //禁止 elementsdialog的css
                      setTimeout(()=>{
                        $(dialogCom).css('marginTop','0').css('top',10);
                        var dialogBody=/*el-dialog__body*/$(dialogCom).find(`.el-dialog__body`)
                        var dialogFooter=$(dialogCom).find(`>.el-dialog__footer`);
                        console.log("=>(modifyDialog3.jsx:144) dialogFooter", dialogFooter,dialogFooter?.innerHeight() );
                        var _height=($('body').height()-dialogBody.offset().top-(dialogFooter?.innerHeight()||0))||817
                        console.log("=>(modifyDialog3.jsx:144) _height",dialogBody, _height);
                        $(dialogBody).css('height',_height);
                        $(dialogBody).css('maxHeight',_height);
                        //   $(dialogBody).css('height',120);
                      });
                    }

                    if(options?.hiddenTitle){
                         $(dialogCom)?.find('.el-dialog__header').css('display','none')
                    }


                  },

                }
            },
            triggerFullSearch(e) {
                this.fullscreen = !this.fullscreen
                var dialogDom = $(e.target).parents('.el-dialog')
                if (this.fullscreen) {
                    setTimeout(() => {
                        dialogDom && dialogDom.css({ top: '0', left: '0' })
                    })
                    //设置弹出框的位置 position:top：0px;left:0px;
                } else {
                    setTimeout(() => {
                        dialogDom &&
                            dialogDom.css({
                                top: `calc(50% - ${$(dialogDom).height() / 2}px)`,
                                left: `calc(50% - ${$(dialogDom).width() / 2}px)`,
                            })
                    })
                }
            },
            closeDialog(result) {
                this.dialogVisible = false

                this.$el&&this.$el.remove&&
                this.$el.remove();



                this.$refs['modify']&&
                this.$refs['modify'].destroyed && this.$refs['modify'].destroyed &&
                this.$refs['modify'].destroyed()

                //关闭弹出框的option hook
                options && options.destroyed && options.destroyed()
                options && options.destroyed && options.destroyed()


                if(result&&result.success){
                    this.promiseObject && this.promiseObject.resolve && this.promiseObject.resolve(result||{success:true})
                }else{
                    this.promiseObject && this.promiseObject.reject && this.promiseObject.reject(result||{success:false})
                }

            }
        },
        render(h) {
            var self = this

            function beforeClose(dom) {
              // 有配置需要二次确认后关闭弹出层or抽屉
              if (options && options.beforeClose) {
                options.beforeClose(dom)
              }else{
                 self.$data.dialogVisible = false
                self.$data.loading = false
                dom && dom.beforeClose && dom.beforeClose();
              }



                return true
            }


            function cancelevent(dom) {
                dom && dom.cancelByDialog && dom.cancelByDialog()
                self.$data.dialogVisible = false
                options && options.cancel && options.cancel()

                self.promiseObject && self.promiseObject.reject && self.promiseObject.reject('取消弹出框')
            }

            async function _successDialog(dom) {
                self.loading = true
                var result = {}
                try {
                    result = await dom.submitByDialog()
                } catch (e) {
                    console.error('dialog submitbydialog', e)
                }
                self.loading = false

                if (result && result.success) {
                    options && options.success && options.success(result)

                    self.promiseObject && self.promiseObject.resolve && self.promiseObject.resolve(result)
                }

                //this.loading = false;
                if (result && result.success) {
                    self.$data.dialogVisible = false

                    self.$refs['modify'].reset && self.$refs['modify'].reset && self.$refs['modify'].reset()
                }
            }

            async function _successThird(dom) {
                self.loading = true
                var result=undefined;
                try {
                    result = await dom.submitByDialogThird()
                } catch (e) {
                    console.error('dialog submitByDialogThird', e)
                }
                self.loading = false
                if (result && result.success) {
                    options && options.success && options.success(result)
                    self.$data.dialogVisible = false

                    self.$refs['modify'].reset && self.$refs['modify'].reset && self.$refs['modify'].reset()

                    self.promiseObject && self.promiseObject.resolve && self.promiseObject.resolve(result)

                }
            }


            var dialogWidth = options.width ? options.width : '800px'
            if (!dialogWidth) {
                dialogWidth = '800px'
            }
            const sureText = self.$data.sureText|| options.sureText || '确定'
            const sureType = options.sureType || 'primary'
            const cancelText = options.cancelText || '取 消'
            const sureTextThird = options.sureTextThird || '保存并审核'
            const thirdButtonType = options.thirdButtonType || 'primary'

            if (options.dialog == 'mydialog') {
                return (
                    <mydialog
                        v-dialog-drag
                        width={dialogWidth}
                        title={options.title}
                        visible={this.$data.dialogVisible}
                        destroyed={options.destroyed}
                        position={options.position}
                        on={this.onevent.call(this)}
                    >


                        <modifyCom immediate={false} isPage={false} ref={'modify'} options={options} />
                        {!(options && options.hiddenFooter) && (
                            <div slot="footer" class="dialog-footer">
                                {
                                    !(options && options.hiddenCancel) && <el-button
                                        onClick={(e) => {
                                            e.stopPropagation()
                                            e.preventDefault()
                                            cancelevent(this.$refs['modify'])
                                        }}
                                    >
                                    {cancelText}
                                    </el-button>
                                }


                                {
                                    //第三个按钮
                                    (!(options && options.hiddenSuccess3)  )&& options.isThirdButton && (
                                        <el-button
                                            type={thirdButtonType}
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                e.preventDefault()
                                                _successThird(this.$refs['modify'])
                                            }}
                                            loading={this.loading}
                                        >
                                            {sureTextThird}
                                        </el-button>
                                    )
                                }



                                {!(options && options.hiddenSuccess) && (
                                    <el-button
                                        type={sureType}
                                        onClick={(e) => {
                                            e.stopPropagation()
                                            e.preventDefault()
                                            _successDialog(this.$refs['modify'])
                                        }}
                                        loading={this.loading}
                                    >
                                        {sureText}
                                    </el-button>
                                )}

                            </div>
                        )}
                    </mydialog>
                )
            }



          // el-drawer el-dialog
          return (
            <DynamicComponent
              custom-class={`dialogClass ${options?.dialogClass}`}
              vDialogDrag
              visible={this.$data.dialogVisible}
              on={this.onevent.call(this)}
              title={options.title}
              showClose={options.showClose}
              fullscreen={this.fullscreen}
              width={dialogWidth}
              size={dialogWidth}
              direction={options?.direction}
              modal={options.modal}
              before-close={() => beforeClose(this.$refs['modify'])}
              close-on-click-modal={options.closeOnClickModal}
              close-on-press-escape	={options?.closeOnPressEscape}
              top={_top}
              destroy-on-close={true}
              wrapperClosable={options?.wrapperClosable}
            >

              {h(titleCom, {
                slot: 'title',
                ref: 'titleRef',
                props: {
                  ...options?._props,
                }
              })}



              <div slot="title" style="position:relative;">
                <span>{options.title}</span>
              </div>
              {h(modifyCom, {
                ref: 'modify',
                props: {
                  ...options?._props,
                  optionsProps: options,
                  immediate: options && options.immediate,
                  isPage: false,
                }
              })}


              {!(this.$data?.hiddenFooter) && (
                <div slot="footer" class="dialog-footer">
                  {!(options && options.hiddenCancel) && (
                    <el-button
                      onClick={(e) => {
                        e.stopPropagation()
                        e.preventDefault()
                        cancelevent(this.$refs['modify'])
                      }}
                    >
                      {cancelText}
                    </el-button>
                  )}

                  {
                    //第三个按钮
                    (!(options && options.hiddenSuccess3)) && options && options.isThirdButton && (
                      <el-button
                        type={thirdButtonType}
                        onClick={(e) => {
                          e.stopPropagation()
                          e.preventDefault()
                          _successThird(this.$refs['modify'])
                        }}
                        loading={this.loading}
                      >
                        {sureTextThird}
                      </el-button>
                    )
                  }


                  {!(this.$data?.hiddenSuccess) && (
                    <el-button
                      type={sureType}
                      onClick={(e) => {
                        e.stopPropagation()
                        e.preventDefault()
                        _successDialog(this.$refs['modify'])
                      }}
                      loading={this.loading}
                    >
                      {sureText}
                    </el-button>
                  )}

                </div>
              )}


              {h(footerCom, {
                slot: 'footer',
                ref: 'footerRef',
                className: 'dialog-footer',
                props: {
                  ...options?._props,
                }
              })}

            </DynamicComponent>
          )
        },
    }
  return formDialog
}
